<style lang="less">
    @import "./agent.less";
</style>
<template>
    <Form ref="userForm" :model="fields" :rules="rules">
        <Row :gutter="16">
            <Col span="8">
            <FormItem label="账号">
                <Input v-model="fields.name" disabled="true"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="邮箱账号" prop="email">
                <Input v-model="fields.email" placeholder="请输入电子邮箱"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="手机号码" prop="mobile">
                <Input v-model="fields.mobile" placeholder="请输入手机号码" maxlength="11"></Input>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="8">
            <FormItem label="真实姓名" prop="realname">
                <Input v-model="fields.realname" placeholder="请输入真实姓名"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="身份证号码" prop="identity_card">
                <Input v-model="fields.identity_card" maxlength="18" placeholder="请输入18位身份证号码"></Input>
            </FormItem>
            </Col>
            <Col span="8">
            <FormItem label="性别" prop="sex">
                <Select v-model="fields.sex">
                    <Option value="0">保密</Option>
                    <Option value="1">男</Option>
                    <Option value="2">女</Option>
                </Select>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="10">
            <FormItem label="省市区" prop="regions">
                <Cascader :data="regions" trigger="hover" v-model="regionSelected"></Cascader>
            </FormItem>
            </Col>
            <Col span="4">
            <FormItem label="重新获取">
                <Button icon="loop" :loading="regionLoading" size="middle" @click="getRegions">刷新</Button>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="详细地址" prop="address">
                <Input v-model="fields.address" placeholder="街道/小区/门牌号"></Input>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16" v-if="false">
            <Col span="6">
            <FormItem label="平台分红" prop="prorations">
                <InputNumber :disabled="disabledEditProrations" :max="100" v-model="fields.prorations.v0">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
            <Col span="6">
            <FormItem label="一级代理分红" prop="prorations">
                <InputNumber :disabled="disabledEditProrations" :max="100" v-model="fields.prorations.v1">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
            <Col span="6">
            <FormItem label="二级代理分红" prop="prorations">
                <InputNumber :disabled="disabledEditProrations" :max="100" v-model="fields.prorations.v2">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
            <Col span="6">
            <FormItem label="三级代理分红" prop="prorations">
                <InputNumber :disabled="disabledEditProrations" :max="100" v-model="fields.prorations.v3">
                </InputNumber><span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="24">
            <FormItem :label="prorationSliderLabel" prop="proration">
                <InputNumber :max="100" :min="0" :precision="0" v-model="fields.proration"></InputNumber>
                <span style="margin-left:5px;font-weight: bold;">%</span>
            </FormItem>
            </Col>
        </Row>
        <Row :gutter="16">
            <Col span="12">
            <FormItem label="密码" prop="password">
                <Input type="password" v-model="fields.password" placeholder="请输入密码"></Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="确认密码" prop="re_password">
                <Input type="password" v-model="fields.re_password" placeholder="请再次输入密码"></Input>
            </FormItem>
            </Col>
        </Row>
        <Row>
            <Col>
            <FormItem>
                <Button type="primary" @click="handleSubmit">提交</Button>
                <Button type="ghost" style="margin-left: 10px" @click="handleCancel">取消</Button>
            </FormItem>
            </Col>
        </Row>
    </Form>
</template>

<script>
    import util from '@/libs/util';
    export default {
        data () {
            const validePhone = (rule, value, callback) => {
                var re = /^1[0-9]{10}$/;
                if (!re.test(value)) {
                    callback(new Error('请输入正确格式的手机号'));
                } else {
                    callback();
                }
            };
            const valideRePassword = (rule, value, callback) => {
                if (this.fields.password.length > 0 && value !== this.fields.password) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            };

            return {
                isShowProrations: false,
                disabledEditProrations: true,
                regionSelected: [],
                regionLoading: false,
                prorationSliderLabel: '',
                fields: {
                    id: '',
                    name: '',
                    mobile: '',
                    email: '',
                    identity_card: '',
                    realname: '',
                    sex: '0',
                    province_code: '',
                    city_code: '',
                    district_code: '',
                    address: [],
                    prorations: {
                        v0: '',
                        v1: '',
                        v2: '',
                        v3: ''
                    },
                    proration: 0,
                    regions: [],
                    password: '',
                    re_password: ''
                },

                rules: {
                    email: [
                        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
                        { type: 'email', message: '电子邮箱格式错误', trigger: 'blur' }
                    ],
                    identity_card: [
                        { required: true, message: '请输入18位身份证号码', trigger: 'blur', min: 18, max: 18 }
                    ],
                    realname: [
                        { required: true, message: '请输入真实姓名, 2~8个字之间', trigger: 'blur', min: 2, max: 8 }
                    ],
                    mobile: [
                        { required: true, message: '请填写手机号码', trigger: 'blur' },
                        { validator: validePhone }
                    ],
                    regions: [
                        { required: true, type: 'array', message: '请选择省市区', trigger: 'change' }
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'blur' }
                    ],
                    address: [
                        { required: true, message: '请输入详细地址', trigger: 'blur' }
                    ],
                    password: [
                        { type: 'string', min: 6, max: 18, massage: '密码必须6~18个字符', trigger: 'blur' }
                    ],
                    re_password: [
                        { validator: valideRePassword, trigger: 'blur' }
                    ]
                }
            }
        },

        watch: {
            regionSelected: function (newVal) {
                this.fields.province_code = newVal[0];
                this.fields.city_code = newVal[1];
                this.fields.district_code = newVal[2];
                this.fields.regions = newVal;
            },

            editItem: function (editItem) {
                this.initFromValues(editItem);
            },

            'fields.proration': function (proration) {
                this.fields.real_proration = this.realProration(this.editItem, proration);
                if (this.editItem.extension.agent_level === 3) {
                    this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                        + '（ 实际占订单收益：' + this.fields.real_proration+ '% ）';
                } else {
                    this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                        + '（ 实际占订单收益[含下一级]：' + this.fields.real_proration+ '% ）';
                }
            }
        },

        props: {
            rootNode: Object,
            regions: [],
            editItem: Object,
            editItemIndex: Number,
            show: Boolean
        },

        created () {
        },

        methods: {
            initFromValues (editItem) {
                const fields = {
                    id: editItem.id,
                    name: editItem.name,
                    mobile: editItem.mobile,
                    email: editItem.email,
                    identity_card: editItem.identity_card,
                    realname: editItem.realname,
                    sex: editItem.sex.toString(),
                    province_code: editItem.province_code,
                    city_code: editItem.city_code,
                    district_code: editItem.district_code,
                    address: editItem.address,
                    prorations: editItem.extension.prorations,
                    proration: editItem.extension.proration,
                    real_proration: editItem.extension.proration,
                    regions: [editItem.province_code, editItem.city_code, editItem.district_code],
                    password: '',
                    re_password: ''
                };

                this.fields = fields;
                this.regionSelected = [fields.province_code, fields.city_code, fields.district_code];

                this.fields.real_proration = fields.proration;

                const loginUser = this.$store.state.user.user;
                let userRoles = loginUser.roles_name || [];
                if (util.anyInOf(userRoles, ['admin', 'system'])) {
                    if (this.editItem.extension.agent_level == 1) {
                        this.isShowProrations = true;
                        this.disabledEditProrations = false;
                    } else {
                        this.isShowProrations = true;
                        this.disabledEditProrations = true;
                    }
                } else {
                    this.isShowProrations = false;
                    this.disabledEditProrations = true;
                }

                this.fields.real_proration  = this.realProration(editItem, fields.proration);

                if (this.editItem.extension.agent_level === 3) {
                    this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                        + '（ 实际占订单收益：' + this.fields.real_proration+ '% ）';
                } else {
                    this.prorationSliderLabel = '分红比例: （ 占上级收益：' + this.fields.proration + '% ）'
                        + '（ 实际占订单收益[含下一级]：' + this.fields.real_proration+ '% ）';
                }
            },

            handleSubmit () {
                this.$refs.userForm.validate((valid) => {
                    if (valid && this.validatorProrations()) {
                        this.editUser(this.fields);
                    } else {
                        this.$Message.error('验证失败');
                    }
                });
            },

            handleCancel () {
                this.rootNode.editModal = false;
            },

            editUser (data) {
                util.api().patch(`/admin/api/agents/${this.editItem.id}`, data).then((resp) => {
                    if (resp.data.status == true) {
                        this.$Message.success(resp.data.message);
                        this.rootNode.editModal = false;
                        this.$emit('on-change', resp.data.data);
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                }).catch((e) => {
                    if (e.response) {
                        if (e.response.status == 422) {
                            if (e.response.data.hasOwnProperty('errors')) {
                                for (let i in e.response.data.errors) {
                                    this.$Notice.error({ title: '表单数据验证失败', desc: e.response.data.errors[i][0] });
                                }
                            }
                        } else {
                            this.$Message.error(e.response.data.message);
                        }
                    }  else {
                        this.$Message.error('网络请求异常');
                    }
                })
            },

            validatorProrations () {
//                if (this.fields.prorations.v0 + this.fields.prorations.v1 + this.fields.prorations.v2 + this.fields.prorations.v3 !== 100) {
//                    this.$Notice.error({ title: '分红比例之和必须等于100%'});
//                    return false;
//                }


                if (this.fields.proration > 100 || this.fields.proration < 0) {
                    this.$Notice.error({ title: '分红比例必须在%1~100%之间'});
                    return false;
                }

                return true;
            },

            getRegions () {
                this.regionLoading = true;
                util.ajax.get('/api/regions/format').then((resp) => {
                    const formatTree = (arr) => {
                        let regions = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].code;
                            node.label = arr[i].name;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children);
                            }

                            regions.push(node);
                        }
                        return regions;
                    };

                    this.regions = formatTree(resp.data.data);
                    this.regionLoading = false;
                }).catch((e) => {
                    this.regionLoading = false;
                    util.handleApiException(e, this, '获取省市区数据失败');
                })
            },

            realProration(user, proration) {
                if (user.extension.agent_level == 1) {
                    return proration;
                } else if (user.extension.agent_level == 2){
                    let _proration = user.extension.parent.extension.proration * proration / 100;
                    return _proration.toFixed(2);
                } else {
                    let agent_v2_ratio = user.extension.parent.extension.parent.extension.proration * user.extension.parent.extension.proration / 100;
                    let _proration = agent_v2_ratio * proration / 100;
                    return _proration.toFixed(2);
                }
            }
        }
    }
</script>
